package com.xiaobai.ThreadPark;

import com.xiaobai.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/*
暂停当前线程
LockSupport.park()
恢复指定线程
LockSupport.unpark(t1)
 */
@Slf4j
public class demo {
    /*
    11:37:37.611 [Thread-0] DEBUG com.xiaobai.ThreadPark.demo -- 开始执行
    11:37:38.617 [Thread-0] DEBUG com.xiaobai.ThreadPark.demo -- park......
    11:37:39.610 [main] DEBUG com.xiaobai.ThreadPark.demo -- unpark......
    11:37:39.611 [Thread-0] DEBUG com.xiaobai.ThreadPark.demo -- 继续执行
    unpark可以在线程暂停前恢复

    wait/notify/notify 和park/unpark的对比

    wait/notify/notify 必须配合Object Monitor使用,而park/unpark不需要

    park&unpark是以线程为单位来【阻塞】和【唤醒】线程的,而notify只能随机唤醒一个线程，
    notifyAll是唤醒所有等待的线程，就不那么精准

    park&unpark是线程间通信的机制，而wait/notify/notifyAll是线程间同步的机制
    park&unpark可以先unpark，而wait/notify/notifyAll不可以
     */
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            log.debug("开始执行");
//            ThreadUtil.sleep(1);
            ThreadUtil.sleep(2);
            log.debug("park......");
            LockSupport.park(); //线程状态是wait  无时限的等待
            log.debug("继续执行");
        });
        t1.start();
//        ThreadUtil.sleep(2);
        ThreadUtil.sleep(1);
        log.debug("unpark......");
        LockSupport.unpark(t1);
    }
}
